package com.nifostasky.config;

import com.nifostasky.properties.MinioProperties;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Objects;

@Slf4j
@Configuration
public class MinioConfig {

//    /**
//     * 7.0.2版本配置
//     * @param minioProperties
//     * @return
//     */
//    @Bean
//    @SneakyThrows
//    public MinioClient minioClient(@Autowired MinioProperties minioProperties) {
//        MinioClient minioClient = new MinioClient(minioProperties.getEndpoint(), minioProperties.getPort(),
//                minioProperties.getAccessKey(), minioProperties.getSecretKey());
//        String defaultBucketName = minioProperties.getDefaultBucketName();
//
//        if(Objects.nonNull(defaultBucketName)) {
//            // 创建默认的bucket
//            if(!minioClient.bucketExists(defaultBucketName)) {
//                log.info("create default bucket \"{}\" success", defaultBucketName);
//                minioClient.makeBucket(defaultBucketName);
//            }
//        }
//        return minioClient;
//    }

    /**
     * 8.3.0版本配置
     */
    @Bean
    @SneakyThrows
    public MinioClient minioClient(@Autowired MinioProperties minioProperties) {
        MinioClient minioClient = MinioClient.builder()
                .endpoint(minioProperties.getEndpoint(), minioProperties.getPort(), false)
                .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
                .build();
        String defaultBucketName = minioProperties.getDefaultBucketName();

        if(Objects.nonNull(defaultBucketName)) {
            BucketExistsArgs bucketExistsArgs = BucketExistsArgs.builder()
                    .bucket(defaultBucketName)
                    .build();
            // 创建默认的bucket
            if(!minioClient.bucketExists(bucketExistsArgs)) {
                MakeBucketArgs makeBucketArgs = MakeBucketArgs.builder()
                        .bucket(defaultBucketName)
                        .build();
                minioClient.makeBucket(makeBucketArgs);
                log.info("create default bucket \"{}\" success", defaultBucketName);
            }
        }

        return minioClient;
    }
}
